import { defineStore } from "pinia";
import Layout from "/@/layout/index.vue";
import { markRaw } from "vue";

interface RouterType {
  routeList: any[];
}
interface portDataType {
  id: string | number;
  name: string;
  path: string;
  component?: string;
  title?: string;
  icon?: string;
  parentId: number | string;
  sort: number;
  hidden?: boolean;
  children?: portDataType[];
}

// 在此处模拟接口获取路由数据
const portData: portDataType[] = [
  {
    id: 3,
    name: "Dashboard",
    path: "dashboard",
    title: "dashboard",
    parentId: 0,
    sort: 0,
  },
  {
    id: 4,
    name: "DashboardIndex",
    path: "index",
    icon: "dashboard",
    title: "首页",
    parentId: 3,
    sort: 0,
    component: "/dashboard/index",
  },
  {
    id: 5,
    name: "setting",
    path: "setting",
    title: "系统设置",
    icon: "setting",
    parentId: 0,
    sort: 1,
  },
  {
    id: 6,
    name: "SettingIndex",
    path: "menu",
    title: "菜单管理",
    parentId: 5,
    sort: 0,
    component: "/setting/menu",
  },
  {
    id: 7,
    name: "SettingPermission",
    path: "permission",
    title: "权限管理",
    parentId: 5,
    sort: 1,
    component: "/setting/permission",
  },
];
const modules = import.meta.glob("/src/views/**/**.vue");

// 组成根据parentId排列的树状结构
function arrToTree(data: portDataType[]): any[] {
  const result: portDataType[] = [];
  const map = new Map();
  data.forEach((item) => {
    // 存入字典集里
    map.set(item.id, item);
  });
  data.forEach((item) => {
    // 判断字典集里是否有该键
    const parent = map.get(item.parentId);
    if (parent) {
      // ?. 可选链操作符，常用于判断对象里是否有该属性
      // ?? 合并操作符 或等于||，但是不会对左边值进行处理
      (parent?.children ?? (parent.children = [])).push(item);
    } else {
      result.push(item);
    }
  });
  return result;
}
// 组成根据sort排序的router结构
function treeToRouterList(data: portDataType[]): any[] {
  // 先根据sort字段进行排序
  const temp = data.sort((a, b) => {
    return a.sort - b.sort;
  });
  return temp.map((item) => {
    return {
      path: item.parentId === 0 ? "/" + item.path : item.path,
      name: item.name,
      meta: { icon: item.icon, title: item.title },
      component:
        item.parentId === 0
          ? markRaw(Layout)
          : modules[`/src/views${item.component}.vue`],
      children:
        item.children && item.children.length > 0
          ? treeToRouterList(item.children)
          : [],
    };
  });
}
// 确定'/'的redirect指向
function getRedirectPath(item: any) {
  if (item.children && item.children.length > 0) {
    return {
      path: "/",
      redirect: item.path + "/" + getRedirectPath(item.children[0]).redirect,
    };
  } else {
    return {
      path: "/",
      redirect: item.path,
    };
  }
}

export const useActiveRouter = defineStore({
  id: "activeRouter",
  state: (): RouterType => ({
    routeList: [],
  }),
  getters: {
    list(state) {
      return state.routeList;
    },
  },
  actions: {
    getRouteList() {
      return new Promise((resolve, reject) => {
        try {
          const data = arrToTree(portData);
          const temp = treeToRouterList(data);
          if (temp && temp.length > 0) {
            temp.unshift(getRedirectPath(temp[0]));
          }
          this.routeList = temp;
          resolve(this.routeList);
        } catch (error) {
          reject(error);
        }
      });
    },
  },
});
